package com.putao.oauth.code.provider;

import cn.hutool.core.util.ObjectUtil;
import com.putao.oauth.code.service.IPhoneUserDetailService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/*
 @Author:putao
 @Date:2022-06-28 20:50:00
*/
public class PhoneCodeAuthenticationProvider implements AuthenticationProvider {

    /**
     * 第四步
     * 自定义AuthenticationProvider 处理类
     * 	这个类就是真正的处理类，经过TokenGranter后，会找到对应的AuthenticationProvider，
     * 	然后取出参数从数据库（UserDetailService）中查询对应的信息进行匹配，
     */

    private IPhoneUserDetailService phoneUserDetailService;

    public PhoneCodeAuthenticationProvider(IPhoneUserDetailService phoneUserDetailService) {
        this.phoneUserDetailService = phoneUserDetailService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 处理逻辑
        PhoneCodeAuthenticationToken authenticationToken = (PhoneCodeAuthenticationToken) authentication;
        //email
        String phone = (String)authentication.getPrincipal();
        String code =(String) authentication.getCredentials();
        UserDetails userDetails = phoneUserDetailService.loadUserByPhone(phone, code);
        if (ObjectUtil.isEmpty(userDetails)) {
            throw new BadCredentialsException("手机号码或者验证码错误");
        }
        PhoneCodeAuthenticationToken authenticationResult = new PhoneCodeAuthenticationToken(userDetails, code, userDetails.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // No AuthenticationProvider found for
        return PhoneCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
